package com.baizhi.controller;

import com.baizhi.entity.Admin;
import com.baizhi.service.AdminService;
import com.baizhi.util.ImageCodeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;


@CrossOrigin  //解决跨域
@RestController  //交给工厂  返回json
@RequestMapping("admin")

public class AdminController {

    private static final Logger log = LoggerFactory.getLogger(AdminController.class);
    @Resource
    AdminService adminService;

    @PostMapping ("getImageCodes")
    public String getImageCode(HttpServletRequest request){
        //1.获取验证码随机字符
        String code = ImageCodeUtil.getSecurityCode();
        //2.获取日志
            log.info("验证码"+code);
        //3.存储验证码随机字符
        request.getServletContext().setAttribute("code",code);

        //5.图片响应前台
        String imgBase64 = null;
        try {
            //4.生成验证码格式图片转为base64格式
           imgBase64 = ImageCodeUtil.careateImgBase64(code);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imgBase64;
    }
    @PostMapping("login")
    public HashMap<String, Object> login(@RequestBody Admin admin, String enCode){
        log.info("接收用户输入的admin:{}",admin);
        log.info("接收用户输入的验证码:{}",enCode);
        HashMap<String, Object> map = adminService.login(admin, enCode);
        return map;

    }
    @PostMapping("logout")
    public void logout(HttpServletRequest request){

        log.info("退出登录");
            //移除登录标记
        request.getServletContext().removeAttribute("admin");
    }
    @RequestMapping("queryAllPage")
    public HashMap<String,Object> queryAllPage(Integer page,Integer pageSize){
        log.info("当前页:{}",page);
        log.info("每页展示条数:{}",pageSize);
        HashMap<String, Object> map = adminService.queryAllPage(page, pageSize);
        return map;
    }
    @RequestMapping("update")
    public HashMap<String,Object> update(@RequestBody Admin admin){
        log.info("修改用户数据:{}",admin);
        return  adminService.update(admin);
    }

    @RequestMapping("delete")
    public HashMap<String,Object> delete(@RequestBody Admin admin) {
        //收集参数
        log.info("接受删除的数据feedback:{}", admin);
        //调用业务
        HashMap<String, Object> map = adminService.delete(admin);
        //返回数据
        return map;
    }
}
